<?

$fields = Tree($params['fields'], 'id', 'container_id', 'fields', true);
$html = "";
foreach ($fields as $field) {
    $field_html = "";
    $field['field_type'] = BDSFields::GetType($field['field_type']);
    $multi = $field['multi'] ? "[]" : "";
    $field_html = "<label for=\"" . $field['code'] . "\">" . $field['title'] . ": </label>";
    $values = BDSFieldValues::GetList(array('field_id' => $field['id'], 'parent_id' => $params['parent_id'], $relation = $params['relation']));
    $value_res = array();
    foreach($values as $v){
        $value_res[$v['field_id']] = $v['value'];
    }
    
    $field_value = isset($value_res[$field['id']]) ? $value_res[$field['id']] : $field['default_value'];    
    if ($field['field_type']['type'] == "select") {
        $field_html .= "<select name=\"fields[" . $field['id'] . "]" . $multi . "\">";
        foreach ($field['fields'] as $option) {
            $selected = $field_value == $option['code'] ? "selected=\"selected\"" : "";
            $field_html .= "<option $selected value=\"" . $option['code'] . "\">" . $option['title'] . "</option>";
        }
        $field_html .= "</select>";
    }elseif($field['field_type']['type'] == "text"){
        $field_html .= "<input type=\"text\" name=\"fields[" . $field['id'] . "]" . $multi . "\" value=\"".(isset($value_res[$field['id']]) ? $value_res[$field['id']] : $field['default_value'])."\">";
    }elseif($field['field_type']['type'] == "textarea"){
        $field_html .= "<br /><textarea cols='60' rows='15' type=\"text\" name=\"fields[" . $field['id'] . "]" . $multi . "\">";
        $field_html .= isset($value_res[$field['id']]) ? $value_res[$field['id']] : $field['default_value'];
        $field_html .= "</textarea>";
    }elseif($field['field_type']['type'] == "file"){
        $field_html .= "<span class=\"current_file\">$field_value</span>";
        $field_html .= "<input type=\"file\" name=\"fields[" . $field['id'] . "]" . $multi . "\" >";
        $field_html .= "<input type=\"hidden\" name=\"fields[" . $field['id'] . "]\" value=\"".$field_value."\">";        
    }
    
    if ($multi) {
        $field_html .= "<a href=\"javascript:oneMoreFiled(" . $field['id'] . ")\" class=\"oneMoreFiled\">+</a>";
    }
    $html .= "<div class=\"field\">" . $field_html . "</div>";
}

$result = $html;
